﻿#pragma once

#include "file.h"
#include <sys/stat.h>

namespace os
{
    inline bool path_exists(const file_path_t &file_path) noexcept
    {
        struct stat buffer;
        return (::stat(file_path.c_str(), &buffer) == 0);
    }

    inline std::size_t file_size(std::FILE *file)
    {
        if (nullptr == file)
        {
            //__throw_exception_again
            throw;
        }
        int fd = ::fileno(file);
        struct stat64 st;
        if (::fstat64(fd, &st) == 0)
        {
            return static_cast<std::size_t>(st.st_size);
        }
        return 0u;
    }

    inline filename_t dir_name(const file_path_t &file_path) noexcept
    {
        auto pos = file_path.find_last_of(s_folder_sep);
        return pos != file_path_t::npos ? file_path.substr(0, pos) : filename_t();
    }

    inline bool fopen(std::FILE* &fp, const filename_t &filename, const std::string &mode)
    {
#ifdef _WIN32
        return false;
#else
        fp = std::fopen(filename.c_str(), mode.c_str());
        return fp != nullptr;
#endif
    }

    inline void fclose(std::FILE* fp)
    {
        if (std::fclose(fp) != 0)
        {
            perror("关闭文件失败");
        }
    }
    
    inline void fwrite(std::FILE* fp, const char* buffer, std::size_t count)
    {
        if (std::fwrite(buffer, 1, count, fp) != count)
        {
            perror("写入文件失败");
        }
    }

    inline void fflush(std::FILE* fp)
    {
        if (std::fflush(fp) != 0)
        {
            perror("刷新输出缓冲区失败");
        }
    }
}  // namesapce os